package com.ruoyi.common.core.domain;

import com.ruoyi.common.enums.ResultCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * 响应信息主体
 */
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(value = "响应信息主体")
public class R<T> implements Serializable {
	private static final long serialVersionUID = 1L;

	@Getter
	@Setter
	@ApiModelProperty(value = "返回标记：成功标记=200，失败标记=500")
	private int code;

	@Getter
	@Setter
	@ApiModelProperty(value = "返回信息")
	private String msg;


	@Getter
	@Setter
	@ApiModelProperty(value = "数据")
	private T data;

	public static <T> R<T> ok() {
		return restResult(null, ResultCode.SUCCESS);
	}

	public static <T> R<T> ok(T data) {
		return restResult(data, ResultCode.SUCCESS);
	}

	public static <T> R<T> ok(T data, String msg) {
		return restResult(data, ResultCode.SUCCESS);
	}

	public static <T> R<T> failed() {
		return restResult(null, ResultCode.FAILED);
	}

	public static <T> R<T> failed(String msg) {
		return restResult(null, ResultCode.FAILED, msg);
	}

	public static <T> R<T> failed(T data) {
		return restResult(data, ResultCode.FAILED, null);
	}

	public static <T> R<T> failed(T data, String msg) {
		return restResult(data, ResultCode.FAILED, msg);
	}

	public static <T> R<T> failed(T data, ResultCode resultCode) {
		return restResult(data, resultCode);
	}

	/**
	 * 参数验证失败返回结果
	 */
	public static <T> R<T> validateFailed() {
		return failed(null, ResultCode.VALIDATE_FAILED);
	}

	/**
	 * 参数验证失败返回结果
	 *
	 * @param message 提示信息
	 */
	public static <T> R<T> validateFailed(String message) {
		return new R<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null);
	}

	/**
	 * 未登录返回结果
	 */
	public static <T> R<T> unauthorized(T data) {
		return new R<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
	}

	/**
	 * 未授权返回结果
	 */
	public static <T> R<T> forbidden(T data) {
		return new R<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
	}

	public static <T> R<T> result(ResultCode resultCode) {
		return restResult(null, resultCode);
	}

	public static <T> R<T> restResult(T data, int code, String msg) {
		R<T> apiResult = new R<>();
		apiResult.setCode(code);
		apiResult.setData(data);
		apiResult.setMsg(msg);
		return apiResult;
	}

	private static <T> R<T> restResult(T data, ResultCode resultCode) {
		R<T> apiResult = new R<>();
		apiResult.setCode(resultCode.getCode());
		apiResult.setData(data);
		apiResult.setMsg(resultCode.getMessage());
		return apiResult;
	}

	private static <T> R<T> restResult(T data, ResultCode resultCode, String msg) {
		R<T> apiResult = new R<>();
		apiResult.setCode(resultCode.getCode());
		apiResult.setData(data);
		apiResult.setMsg(msg);
		return apiResult;
	}
}
